﻿using System.Collections.Generic;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.Graphics;
using Phoenix.Xna.Framework.Graphics.Models;
using Phoenix.Xna.Framework.Reflection;

namespace Phoenix.Xna.Framework.ContentPipeline.Models
{
    public class InstancedModelReader : ContentTypeReader<InstancedModel>
    {
        protected override InstancedModel Read(ContentReader input, InstancedModel existingInstance)
        {
            int count = input.ReadInt32();
            List<InstancedModelPart> parts = new List<InstancedModelPart>();
            List<Effect> effects = new List<Effect>();

            for (int i = 0; i < count; i++)
            {
                InstancedModelPart p = input.ReadObject<InstancedModelPart>();
                parts.Add(p);
            }

            InstancedModel im = ReflectionHelper.CreateInstance<InstancedModel>();
            ReflectionHelper.SetField<InstancedModel>(im, "_modelParts", parts);

            if (existingInstance == null)
            {
                existingInstance = ReflectionHelper.CreateInstance<InstancedModel>();
            }

            if (im != null)
            {
                existingInstance = im;
            }

            return im;
        }
    }
}
